package com.gz.mylife.app;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ListView;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.adapter.ChattingAdapter;
import com.gz.mylife.widget.OfflineDialog;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.account.po.UserInfo;
import com.zl.smartmall.library.im.IM;
import com.zl.smartmall.library.im.po.MessageInfo;
import com.zl.smartmall.library.im.vo.MessageInfoDao;
import com.zl.smartmall.library.im.vo.SessionInfoDao;
import com.zl.smartmall.library.listener.MessageListener;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;

public class PrivateLetter extends BaseActivity implements OnRefreshListener<ListView>, OnClickListener, Observer {
	
	private static final String TAG = PrivateLetter.class.getSimpleName();
	private int mMyUid;
	private int mReceiverGender;
	private int mReceiverUid;
	private String mReceiverFace;
	private String mReceiverName;
	
	private ChattingAdapter mAdapter;
	private MessageInfoDao mMessageInfoDao;
	private MyHandler mHandler;
	private SessionInfoDao mSessionInfoDao;
	private UserInfo mUserInfo;
	private MessageListener mSendMessageListener;

	private EditText mEditMessage;
	private OfflineDialog mOfflineView;
	private PullToRefreshListView mListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_private_letter);

		mMyUid = PreferenceModel.getInt(Constants.PREFERENCE_KEY_UID, -1);
		mReceiverName = getIntent().getStringExtra("name");
		mReceiverUid = getIntent().getIntExtra("uid", 0);
		mReceiverGender = getIntent().getIntExtra("gender", 0);
		mReceiverFace = getIntent().getStringExtra("face");
		mUserInfo = IAuth.getInstance().loadUserInfo();
		mHandler = new MyHandler(this);
		mAdapter = new ChattingAdapter(getApplicationContext(), new ArrayList<MessageInfo>());
		mMessageInfoDao = new MessageInfoDao(getApplicationContext());
		mSessionInfoDao = new SessionInfoDao(getApplicationContext());
		initListener();

		findViewById(R.id.btn_send).setOnClickListener(this);
//		mActionBar.setTitle("与" + mReceiverName + "对话");
		setActionbarTitle("与" + mReceiverName + "对话", false);
		mEditMessage = (EditText) findViewById(R.id.et_message);
//		mEditMessage.setOnClickListener(this);
		mListView = (PullToRefreshListView) findViewById(R.id.listview);
		mListView.setAdapter(mAdapter);
//		mListView.setOnItemClickListener(this);
		mListView.setOnRefreshListener(this);
		
		loadCacheFromDB();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mHandler.release();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
//		MessageWorker.getInstance().registerObserver(Define.OBSERVER_PRIVATE_LETTER, this);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
//		MessageWorker.getInstance().unRegisterObserver(Define.OBSERVER_PRIVATE_LETTER, this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.private_letter, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_send:
			if(!TextUtils.isEmpty(mEditMessage.getText().toString())) {
				addMessage(mEditMessage.getText().toString());
				IM.getInstance().sendTextMessage(mEditMessage.getText().toString(), 
						mReceiverUid, mSendMessageListener);
				mEditMessage.getText().clear();
			}
			break;
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
//		ThreadExecutor.getInstance().execute(new Runnable() {
//			
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				android.os.Message msg = mHandler.obtainMessage(Define.MSG_LOAD_CHAT_RECORD_FINISH);
//				msg.obj = mMessageInfoDao.query(Tools.obtainRelativeChatID(mMyUid, mReceiverUid), mAdapter.getCount());		
//				msg.sendToTarget();
//			}
//		});
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
//		Message message = (Message) data;
//		if(message.type == Define.OBSERVER_PRIVATE_LETTER) {
//			MessageInfo info = (MessageInfo) message.data;
//			mAdapter.add(info);
//			mListView.getRefreshableView().setSelection(mAdapter.getCount() - 1);
//		}
	}
	
	private void addMessage(String msg) {
		MessageInfo info = new MessageInfo();
		info.setSendFrom(Constants.IM_MSG_SEND_FROM_ME);
		info.setMessage(msg);
		info.setSenderFace(mUserInfo.getFace());
		info.setSenderNickname(mUserInfo.getNickname());
		info.setSenderUid(mUserInfo.getUid());
		mAdapter.add(info);
		mListView.getRefreshableView().setSelection(mAdapter.getCount() - 1);
	}
	
	private void initListener() {
		mSendMessageListener = new MessageListener() {
			
			@Override
			public void onOffline() {
				// TODO Auto-generated method stub
				mOfflineView.show();
			}
			
			@Override
			public void onNoNetWork() {
				// TODO Auto-generated method stub
				CrashHandler.d(TAG, Define.MSG_NO_NETWORK);
			}
			
			@Override
			public void onSendMessageSuccess(List<MessageInfo> messageInfos) {
				// TODO Auto-generated method stub
				CrashHandler.d(TAG, "消息发送成功");
			}
			
			@Override
			public void onSendMessageFailure() {
				// TODO Auto-generated method stub
				CrashHandler.d(TAG, "消息发送成功");
			}
		};
	}
	
//	private void initHttpHandler() {		
//		mMsgHttpHandler = new SendMessageHttpHandler() {
//			
//			@Override
//			public void onSendMessageSuccess(MessageInfo messageInfo) {
//				// TODO Auto-generated method stub
//				CrashHandler.d(TAG, "消息发送成功, 内容为：" + messageInfo.getMessage());
//				messageInfo.setRelativeID(Tools.obtainRelativeChatID(mMyUid, mReceiverUid));
//				messageInfo.setDisplayLocation(Define.CHAT_MSG_DISPLAY_LOCATION_ME);
//				mMessageInfoDao.insert(messageInfo);
//				SessionInfo sessionInfo =  new SessionInfo();
//				sessionInfo.setFace(messageInfo.getReceiverFace());
//				sessionInfo.setMessage(messageInfo.getMessage());
//				sessionInfo.setNickname(messageInfo.getReceiverNickname());
//				sessionInfo.setUid(messageInfo.getReceiverUid());
//				sessionInfo.setTime(System.currentTimeMillis());
//				mSessionInfoDao.delete(sessionInfo.getUid());
//				mSessionInfoDao.insert(sessionInfo);
//				//更新会话列表数据
//				MessageWorker.getInstance().dispatchMessage(Define.OBSERVER_SESSION_LIST, sessionInfo);
//			}
//			
//			@Override
//			public void onSendMessageFailure(int errorCode) {
//				// TODO Auto-generated method stub
//				ToastUtils.showToast(PrivateLetter.this, "消息发送失败");
//			}
//			
//			@Override
//			public void onError(Throwable error) {
//				// TODO Auto-generated method stub
//				ToastUtils.showToast(PrivateLetter.this, "消息发送失败");
//			}
//		};
//	}
	
	private void loadCacheFromDB() {
//		ThreadExecutor.getInstance().execute(new Runnable() {
//			
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				mUserInfo = mUserInfoDao.query(mMyUid);
//				android.os.Message msg = mHandler.obtainMessage(Define.MSG_LOAD_CACHE_FINISH);
//				msg.obj = mMessageInfoDao.query(Tools.obtainRelativeChatID(mMyUid, mReceiverUid), mAdapter.getCount());	
//				msg.sendToTarget();			
//			}
//		});
	}
	
	static class MyHandler extends Handler {
		
		private PrivateLetter mOuter;
		
		public MyHandler(PrivateLetter outer) {
			// TODO Auto-generated constructor stub
			mOuter = outer;
		}
		
		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
//			switch (msg.what) {
//			case Define.MSG_LOAD_CACHE_FINISH:
//				mOuter.mAdapter.addAll((List<MessageInfo>) msg.obj);
//				mOuter.mListView.getRefreshableView().setSelection(
//						mOuter.mAdapter.getCount() - 1);
//				break;
//				
//			case Define.MSG_LOAD_CHAT_RECORD_FINISH:
//				int position = mOuter.mListView.getRefreshableView().getSelectedItemPosition();
//				mOuter.mAdapter.addAll((List<MessageInfo>) msg.obj, 0);
//				mOuter.mListView.onRefreshComplete();
//				mOuter.mListView.getRefreshableView().setSelection(position + 10);
//				break;
//			}
		}
		
		public void release() {
			new WeakReference<PrivateLetter>(mOuter);
		}
	}

}
